package com.wei.web.middleware.httpfilter.registrar.filter;

import com.wei.web.middleware.httpfilter.registrar.model.FilterConfigDTO;
import com.wei.web.middleware.httpfilter.registrar.model.RegisterContext;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.web.filter.GenericFilterBean;

public class CustomFilterClassRegistrar extends AbstractFilterRegistrar {

    public static final String TYPE = "customFilterClass";

    @Override
    public String getType() {
        return TYPE;
    }

    @Override
    public void registrar(FilterConfigDTO filterConfigDTO, BeanDefinitionRegistry registry, RegisterContext registerContext) {
        GenericFilterBean filter = null;
        try {
            Class<?> filterClass = Class.forName(filterConfigDTO.getClassName());

            Object customFilter = filterClass.newInstance();
            if (! (customFilter instanceof GenericFilterBean)) {
                throw new RuntimeException("not a filter");
            }
            filter = (GenericFilterBean)customFilter;
        } catch (ClassNotFoundException|InstantiationException|IllegalAccessException e) {
            throw new RuntimeException(e);
        }

        String filterName = getFilterNameWithDefault(filterConfigDTO, registerContext);
        doRegisterWithObject(filterConfigDTO, filterName,
                registerContext.getFilterOrder(),
                filterConfigDTO.getUrlPatterns(),
                filter,
                registry);

    }
}
